package YZ.Students.Mier.Service.impl;

import YZ.Students.Mier.Dao.BaseDao;
import YZ.Students.Mier.Dao.UserDao;
import YZ.Students.Mier.Dao.impl.UserDaoImpl;
import YZ.Students.Mier.Service.UserService;
import YZ.Students.Mier.Tool.utils.PasswordUtils;
import YZ.Students.Mier.Tool.utils.UuidUtils;
import YZ.Students.Mier.entity.UserEntity;
import jdk.nashorn.internal.ir.ReturnNode;
import lombok.SneakyThrows;

import javax.imageio.spi.RegisterableService;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @className: UserServiceImpl
 * @author: shuishui
 * @date: 2022/12/03 8:52
 */
public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    protected BaseDao<UserEntity> getBaseDao() {
        return userDao;
    }
    @Override
    public void register(UserEntity userEntity) throws Exception {
        userEntity.setPassword(PasswordUtils.hashPw(userEntity.getPassword()));
        userEntity.setStatus(1);
        userEntity.setCreateTime(new Date());
        userEntity.setActivationCode(UuidUtils.getld());
        userEntity.setType(0);
        int save = userDao.insert(userEntity);
    }
    @Override
    public UserEntity byActivationCode(String activationCode) throws Exception{
        return userDao.selectByActivationCode(activationCode);
    }

    @Override
    public UserEntity login(String username, String password) throws Exception {
        UserEntity userEntity = userDao.selectByUsername(username);

        if (userEntity == null) {
            return null; // 用户名不存在
        }

        // 2、密码的比对
        if (!PasswordUtils.check(password, userEntity.getPassword())) {
            return null;
        }

        return userEntity;
    }

    @Override
    public void updateHeaderUrl(Integer id, String filePath) throws Exception {
        userDao.updateHeaderUrl(id,filePath);
    }

    @SneakyThrows
    @Override
    public boolean changePassword(Map mapp, Integer id) {
        UserEntity userEntity = userDao.selectById(id);
        String password =  PasswordUtils.hashPw(mapp.get("oldPassword").toString());
        boolean result = PasswordUtils.check(password,userEntity.getPassword());
        if (!result){
            return false;
        }
        String newPassword = mapp.get("newPassword").toString();
        Integer result2 = userDao.changePassword(id,newPassword);
        if (result2==null){
            return false;
        }
        return true;
    }

}
